#include "leavewidget.h"
#include "ui_leavewidget.h"
#include "leaveapplydialog.h"
#include "loginwidget.h"
#include <QDateTime>
#include <QMessageBox>
#include <QDebug>

LeaveWidget::LeaveWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LeaveWidget)
{
    ui->setupUi(this);
    initWidget();
    initTable();
}

LeaveWidget::~LeaveWidget()
{
    delete ui;
}

void LeaveWidget::flushTable()
{
    initTable();
}

/**
 * @brief 初始化窗体
 */
void LeaveWidget::initWidget()
{
    this->setWindowTitle("请销假");
}

/**
 * @brief 初始化Table
 */
void LeaveWidget::initTable()
{
    model = new QSqlTableModel(this);
    model->setTable("leave_record"); //指定表
    model->setFilter(QString("leave_username = '%1' AND is_back=0").arg(LoginWidget::userName));
    model->setHeaderData(2,Qt::Horizontal,"请假事由");
    model->setHeaderData(3,Qt::Horizontal,"请假起始时间");
    model->setHeaderData(4,Qt::Horizontal,"请假结束时间");
    model->setHeaderData(7,Qt::Horizontal,"审批是否通过");
    model->select(); //查询
    model->setEditStrategy(QSqlTableModel::OnManualSubmit); //Model编辑策略，提交生效
    ui->tableView->setModel(model); //将模型设置到视图中
    ui->tableView->setColumnHidden(0, 1); //隐藏编号列
    ui->tableView->setColumnHidden(1, 1); //隐藏用户ID列
    ui->tableView->setColumnHidden(5, 1); //隐藏真实结束时间列
    ui->tableView->setColumnHidden(6, 1); //隐藏是否销假列
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);   //使其不可编辑
}

/**
 * @brief 请假
 */
void LeaveWidget::on_btn_leave_clicked()
{
    LeaveApplyDialog *dialog = new LeaveApplyDialog();
    connect(dialog, SIGNAL(closeAndFlush()), this, SLOT(flushTable()));
    dialog->show();

}

/**
 * @brief 销假
 */
void LeaveWidget::on_btn_leave_back_clicked()
{
    int curRow = ui->tableView->currentIndex().row(); //获取选中行号
    if (curRow < 0)
    {
        QMessageBox::warning(this, tr("提示"), tr("请选择要销假的记录"), QMessageBox::Ok);
        return;
    }
    QString isApproved = model->itemData(model->index(curRow, 7))[0].toString(); //获取是否审批成功
    if (isApproved == "审批通过")
    {
        model->setData(model->index(curRow, 6), 1); //是否销假置为1
        model->setData(model->index(curRow, 5), QDateTime::currentDateTime().toString());
        model->submitAll();
        QMessageBox::information(this, tr("提示"), tr("销假成功"), QMessageBox::Ok);
    }
    else if (isApproved == "未审批")
    {
        QMessageBox::warning(this, tr("提示"), tr("申请待批准，不能销假"), QMessageBox::Ok);
    }
    else if (isApproved == "审批不通过")
    {
        QMessageBox::warning(this, tr("提示"), tr("申请未通过，不能销假"), QMessageBox::Ok);
    }

}
